﻿using Microsoft.EntityFrameworkCore;
using System.Security.Claims;

namespace EasyDDD.AdminModule.Records
{
    public class SysAdminRoleRecords : EasyDDD.Infrastructure.EFCore.Records.Records<AdminModuleRecordsDbContext, Entities.ApplicationRole>
    {
        public SysAdminRoleRecords(AdminModuleRecordsDbContext DbContext) : base(DbContext)
        {
        }


        // 根据角色ID获取角色对应的声明
        public async Task<List<Claim>> GetClaims(Guid[] roleIds)
        {
            var claims = new List<Claim>();

            // 获取角色对应的代码
            var roles = await this.AsQueryable()
                 .Where(e => roleIds.Contains(e.Id))
                 .Select(e => e.Code)
                 .ToListAsync();
            foreach (var code in roles)
            {
                // 添加角色声明
                claims.Add(new Claim(ClaimTypes.Role, code));
            }
            // 获取角色对应的声明列表
            //var claimList = await this.AsQueryable()
            //    .Where(e => roleIds.Contains(e.Id))
            //    //.SelectMany(e => e.RoleClaimList.Select(e => new Claim(e.ClaimType, e.ClaimValue)))
            //    //.SelectMany(e => e.RoleClaimList.Select(f => new { ApplicationRoleId = f.RoleId, f.ClaimType, f.ClaimValue }))
            //    .Distinct()
            //    .ToListAsync();
            //foreach (var claim in claimList)
            //{
            //    // 添加声明
            //    claims.Add(new Claim(claim.ClaimType, claim.ClaimValue));
            //}

            var claimList = await this.DbContext.Set<Entities.ApplicationRole>()
                .Join(this.DbContext.Set<Entities.ApplicationRoleClaim>(), r => r.Id, rc => rc.RoleId, (r, rc) => new { r, rc })
                .Where(e => roleIds.Contains(e.r.Id))
                .Select(e => new Claim(e.rc.ClaimType, e.rc.ClaimValue))
                .Distinct()
                .ToListAsync();
            foreach (var claim in claimList)
            {
                // 添加声明
                claims.Add(claim);
            }

            return claims;
        }
    }
}
